import Foundation
import Flutter
import UIKit
import HelpDesk
import Hyphenate


public class  CpdEasemobCECPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "cpd_easemob_cec", binaryMessenger: registrar.messenger())
    let instance = CpdEasemobCECPlugin()
    HxChatManage.shared.register(registrar: registrar);
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        //    result("iOS " + UIDevice.current.systemVersion)
        print(call.method)

        switch call.method {

        case "init":
            initMethod(call: call, result: result)
            break;
        case "register":
            registerMethod(call: call, result: result)
            break;
        case "login":
            loginMethod(call: call, result: result)

        case "loginWithToken":
            loginWithToken(call: call, result: result)
            break;
        case "isLoggedInBefore":
            isLoginMethod(call: call, result: result)
            break;
        case "logout":
            logoutMethod(call: call, result: result)
            break;
        case "sendMessage":
            sendMessage(call: call, result: result)
            break;
        case "loadMessages":
            loadMessages(call: call, result: result)
            break;
        case "getAllMessage":
            getAllMessage(call: call, result: result)
            break;
        case "unreadMessageCount":
            unreadMessageCount(call: call, result: result)
            break;
        case "markAllMessageAsRead":
            markAllMessageAsRead(call: call, result: result)
            break;
        case "sendEvalMessage":
            sendEvalMessage(call: call, result: result)
            break;

        default:
            return
        }


    }


    public func initMethod(call: FlutterMethodCall, result: @escaping FlutterResult){
        let option = HDOptions()
        let args = call.arguments  as! [String:Any]
        let arguments = args["args"] as! [String:Any];

        option.appkey = arguments["appKey"] as? String
        option.tenantId = arguments["tenantId"] as? String
        let error =  HDClient.shared().initializeSDK(with: option)
        guard error == nil else{
            result(FlutterError(code: String(describing: error?.code.rawValue), message: error?.errorDescription, details: nil))
            return
        }
        result(true)
        HxChatManage.shared.setEventMessage()

    }


    public func registerMethod(call: FlutterMethodCall, result: @escaping FlutterResult){
        let args = call.arguments  as! [String:Any]
        let arguments = args["args"] as! [String:Any];


        let username = arguments["username"] as? String
        let password = arguments["password"] as? String
        let error =  HDClient.shared().register(withUsername: username, password: password)
        guard error == nil else{
            result(FlutterError(code: String(describing: error?.code.rawValue), message: error?.errorDescription, details: nil))
            return
        }
        result(true)


    }

    public func loginMethod(call: FlutterMethodCall, result: @escaping FlutterResult){
        let args = call.arguments  as! [String:Any]
        let arguments = args["args"] as! [String:Any];

        let username = arguments["username"] as? String
        let password = arguments["password"] as? String
        let error = HDClient.shared().login(withUsername: username, password: password)
        guard error == nil else{
            result(FlutterError(code: String(describing: error?.code.rawValue), message: error?.errorDescription, details: nil))
            return
        }
        result(true)

    }

    public func loginWithToken(call: FlutterMethodCall, result: @escaping FlutterResult){
        let args = call.arguments  as! [String:Any]
        let arguments = args["args"] as! [String:Any];

        let username = arguments["username"] as? String
        let token = arguments["token"] as? String
        let error = HDClient.shared().login(withUsername: username, token: token)
        guard error == nil else{
            result(FlutterError(code: String(describing: error?.code.rawValue), message: error?.errorDescription, details: nil))
            return
        }
        result(true)

    }

    public func isLoginMethod(call: FlutterMethodCall, result: @escaping FlutterResult){

        result(HDClient.shared().isLoggedInBefore);
    }

    public func logoutMethod(call: FlutterMethodCall, result: @escaping FlutterResult){

        let error = HDClient.shared().logout(true)
        guard error == nil else{
            result(FlutterError(code: String(describing: error?.code.rawValue), message: error?.errorDescription, details: nil))
            return
        }
        result(true)

    }

    //获取消息
    public func loadMessages(call: FlutterMethodCall, result: @escaping FlutterResult){

        let args = call.arguments  as! [String:Any]
        let arguments = args["args"] as! [String:Any];
        
        let aMessageId = arguments["startMsgId"] as? String ?? ""
        let serviceNumber = arguments["to"] as? String
        let count = arguments["pageSize"] as? Int32 ?? 20
        
        let conversation = HDClient.shared().chatManager.getConversation(serviceNumber)
        conversation!.loadMessagesStart(
            fromId: aMessageId == "" ? nil : aMessageId,
            count: count,
            searchDirection: HDMessageSearchDirectionUp){(aMessages, aError) in
                
                if let error = aError {
                    // 处理错误
                    result(error.errorDescription)
                } else if let messages = aMessages, !messages.isEmpty {
                    // 获取到消息 messages
                    result(MessageManage.messagesToListMap(messages: messages))
                }
            }
    }
    
    //获取最新20条消息
    public func getAllMessage(call: FlutterMethodCall, result: @escaping FlutterResult){
        
        let args = call.arguments  as! [String:Any]
        let arguments = args["args"] as! [String:Any];
        //
        let serviceNumber = arguments["to"] as? String
        //        let count = arguments["pageSize"] as? Int32 ?? 20
        
        let conversation = HDClient.shared().chatManager.getConversation(serviceNumber)
        conversation!.loadMessagesStart(
            fromId: nil,
            count: 20,
            searchDirection: HDMessageSearchDirectionUp){(aMessages, aError) in
                
                if let error = aError {
                    // 处理错误
                    result(error.errorDescription)
                } else if let messages = aMessages, !messages.isEmpty {
                    // 获取到消息 messages
                    result(MessageManage.messagesToListMap(messages: messages))
                }
            }
    }
    
    //unreadMessageCount
    public func unreadMessageCount(call: FlutterMethodCall, result: @escaping FlutterResult){
        
        //        HDConversation *conversation = [[HDClient sharedClient].chatManager getConversation:<#IM 服务号#>];
        //         int unreadCount = conversation.unreadMessagesCount; //获取指定会话的未读消息数
        let args = call.arguments  as! [String:Any]
        let arguments = args["args"] as! [String:Any];
        
        let serviceNumber = arguments["to"] as? String
        let conversation = HDClient.shared().chatManager.getConversation(serviceNumber)
        let unreadCount:Int32 = conversation?.unreadMessagesCount ?? 0;
        result(unreadCount);
        
    }
    
//     markAllMessageAsRead
    public func markAllMessageAsRead(call: FlutterMethodCall, result: @escaping FlutterResult){

        let args = call.arguments  as! [String:Any]
        let arguments = args["args"] as! [String:Any];

        let serviceNumber = arguments["to"] as? String
        let conversation = HDClient.shared().chatManager.getConversation(serviceNumber)
        conversation?.markAllMessages(asRead: nil);

    }

    
    //sendEvalMessage
    public func sendEvalMessage(call: FlutterMethodCall, result: @escaping FlutterResult){
        
        let args = call.arguments  as! [String:Any]
        let arguments = args["args"] as! [String:Any];
        let serviceNumber = arguments["to"] as? String
        let msgId = arguments["msgId"] as? String
        let degree_tags = arguments["degree_tags"] as? String
        let degree_id = arguments["degree_id"] as? String


        ///获取会话
        let conversation = HDClient.shared().chatManager.getConversation(serviceNumber)
        
        ///根据msgID获取评价消息
        let pMessage:HDMessage =  (conversation?.loadMessage(withId: msgId, error:  nil))!
        
        //创建空的文本消息
        let message:HDMessage = HDMessage.createTxtSend(withContent: "", to: serviceNumber)

        //创建HDControlMessage对象
        let hCtrl = HDControlMessage()
        //设置ControlType
        let type = ControlType(value: "enquiry")
        hCtrl.type = type
    
        let ags = ControlArguments()
        //设置sessionId
        var extDict = pMessage.ext as? [String: Any]
        if let weichatDict = extDict!["weichat"] as? [String: Any],
           let serviceSessionDict = weichatDict["service_session"] as? [String: Any],
           let serviceSessionId = serviceSessionDict["serviceSessionId"] as? String {
            ags.sessionId = serviceSessionId
        }
//        [24]    (null)    "ctrlType" : "inviteEnquiry"
        //设置inviteId
        if let weichatDict = extDict!["weichat"] as? [String: Any],
           let ctrlArgsDict = weichatDict["ctrlArgs"] as? [String: Any] {
            ags.inviteId =  String(ctrlArgsDict["inviteId"] as? Int ?? 0)
        }
        
//        ags.evaluateWay = "agent"
        ags.detail = getDetail(id: degree_tags ?? "")
        ags.summary = getScore(id: degree_id ?? "")
        ///设置arguments
        hCtrl.arguments = ags

        
//        let appraiseDict:[String: Any] = ["id": "391119", "name": "已解决"]
//        var array: [[String: Any]] = []
//        array.append(appraiseDict)
//
//        var weichat = (extDict!["weichat"] as? [String: Any])
//        if var ctrlArgs = weichat!["ctrlArgs"] as? [String: Any] {
////            weichat!["ctrlType"] = "enquiry"
//            ctrlArgs["appraiseTags"] = array
//            ctrlArgs["evaluationDegreeId"] = degree_id
//            weichat!["ctrlArgs"] = ctrlArgs
//            extDict!["weichat"] = weichat
//            // 更新 extDict
//            extDict = extDict as AnyObject as? [String: Any]
//        }
        print(NSHomeDirectory())
        message.ext = extDict
        //message添加hCtrl
        message.add(hCtrl)
        
        
        HDClient.shared().chatManager.send(message, progress: nil) {aMessages, aError in
            //发送消息完成，aError为空则为发送成功
            print(aError as Any)
            if let error = aError {
                // 处理错误
                print(error.errorDescription ?? "")
                result(false)
            } else if aMessages != nil {
                // 获取到消息 messages
                result(true)
            }
        }
    }
}

func getScore(id:String) ->String{
    
    switch id {
    case "357115":
        return "5";
    case "357116":
        return "4";
    case "357117":
        return "3";
    case "357118":
        return "2";
    case "357119":
        return "1";
    default:
        return ""
    }
}


func getDetail(id:String) ->String{
    
    
    switch id {
    case "391115":
        return "已解决"
    case "391117":
        return "已解决"
    case "391119":
        return "已解决"
    case "391121":
        return "已解决"
    case "391123":
        return "已解决"
            
    case "391116":
        return "未解决"
    case "391118":
        return "未解决"
    case "391120":
        return "未解决"
    case "391122":
        return "未解决"
    case "391124":
        return "未解决"
        
    default:
        return ""
    }
}

extension CpdEasemobCECPlugin{




    public func sendMessage(call: FlutterMethodCall, result: @escaping FlutterResult){

        let args = call.arguments  as! [String:Any]
        let arguments = args["args"] as! [String:Any];
        let type = arguments["type"] as? String
        ///文字消息
        if type == "text" {

            sendTextMeesage(arguments: arguments, result: result)
        }

        ///图片消息
        else if type == "image" {
            sendImageMeesage(arguments: arguments, result: result)

        }
        ///视频消息
        else if type == "video" {

            sendVideoMeesage(arguments: arguments, result: result)

        }
        ///（语音<VOICE>，
        else if type == "voice" {

            sendVoiceMeesage(arguments: arguments, result: result)
        }
        ///文件消息
        else if type == "file" {

            sendFileMeesage(arguments: arguments, result: result)
        }
        ///自定义消息
        else if type == "custom" {

            result("未实现")
        }
        ///命令<CMD>,
        else if type == "cmd" {

            result("未实现")

        }
        ///位置<LOCATION>）
        else if type == "location" {

            result("未实现")
        }

    }



    //发送消息
    public func sendTextMeesage(arguments: [String:Any],result: @escaping FlutterResult){


//         let text = arguments["content"] as? String
//         let toUser = arguments["to"] as? String
//         print("sendTextMeesage-----\(text)----\(toUser)")
//         let message = HDMessage.createTxtSend(withContent: text, to: toUser)



        var text = ""
        if let argumentText = arguments["content"] as? String {
            text = argumentText
        }
        let toUser = arguments["to"] as? String

//         print("\(arguments["content"] as? String)")
//
//         print(text)

        let message:HDMessage

        var extType = ""
        if let argumentsExtType = arguments["extType"] as? String {
            extType = argumentsExtType
        }

//        message = HDMessage.createTxtSend(withContent: text, to: toUser)
        if(extType == "VisitorMsg"){
            // 发送带访客属性的消息
            message = HDMessage.createTxtSend(withContent: "", to: toUser)
            let visitor:HDVisitorInfo = HDVisitorInfo()
            visitor.qq = arguments["visitor_qq"]as? String
            visitor.companyName = arguments["visitor_companyName"]as? String
            visitor.nickName = arguments["visitor_nickName"]as? String
            visitor.email = arguments["visitor_email"]as? String
            visitor.desc = arguments["visitor_description"]as? String
            visitor.phone = arguments["visitor_phone"]as? String
            visitor.name = arguments["visitor_name"]as? String
            message.add(visitor)


        }else if(extType == "TrackMsg"){
            // 发送轨迹消息
            message = HDMessage.createTxtSend(withContent: "", to: toUser)
            let vst:HDVisitorTrack = HDVisitorTrack()

            vst.title = arguments["track_title"]as? String  //标题
            vst.price = arguments["track_price"]as? String //价格
            vst.desc = arguments["track_desc"]as? String//描述
            vst.imageUrl = arguments["track_imageUrl"]as? String //图片url
            vst.itemUrl = arguments["track_itemUrl"]as? String //点击图片的链接

            message.add(vst)

        }else if(extType == "orderMsg"){
            // 发送订单消息
            message = HDMessage.createTxtSend(withContent: "", to: toUser)
            let ord:HDOrderInfo = HDOrderInfo()

            ord.title = arguments["order_title"]as? String
            ord.orderTitle = arguments["order_orderTitle"]as? String
            ord.price = arguments["order_price"]as? String
            ord.desc = arguments["order_desc"]as? String
            ord.imageUrl = arguments["order_imageUrl"]as? String
            ord.itemUrl = arguments["order_itemUrl"]as? String
            message.add(ord)

        }else{
            //文本消息
            message = HDMessage.createTxtSend(withContent: text, to: toUser)
        }


        HDClient.shared().chatManager.send(message) { progress in
            //发送消息进度
            print(progress)

        } completion: {(aMessages, aError) in
            //发送消息完成，aError为空则为发送成功
            print(aError as Any)
            if let error = aError {
                // 处理错误
                result(error.errorDescription)
            } else if aMessages != nil {
                // 获取到消息 messages
                result(MessageManage.messageToMap(message: aMessages!))
            }
        }

    }


    //发送image消息
    public func sendImageMeesage(arguments: [String:Any],result: @escaping FlutterResult){

        let filePath = arguments["filePath"] as? String ?? ""
        let toUser = arguments["to"] as? String ?? ""
        let image = UIImage(named: filePath)!
        let message = HDMessage.createImageSend(with: image.jpegData(compressionQuality: 1.0), displayName: currentTimeString(), to: toUser)
        HDClient.shared().chatManager.send(message) { progress in
            //发送消息进度 Image
            print(progress)

        } completion: {(aMessages, aError) in
            //发送消息完成，aError为空则为发送成功
            print(aError as Any)
            if let error = aError {
                // 处理错误
                result(error.errorDescription)
            } else if aMessages != nil {
                // 获取到消息 messages
                result(MessageManage.messageToMap(message: message!))
            }
        }

    }


    public func sendVideoMeesage(arguments: [String:Any],result: @escaping FlutterResult){

        let filePath = arguments["filePath"] as? String ?? ""
        let toUser = arguments["to"] as? String ?? ""
        let message = HDMessage.createVideoSend(withLocalPath: filePath, displayName:  currentTimeString(), to: toUser)
        HDClient.shared().chatManager.send(message) { progress in
            //发送消息进度 Image
            print(progress)

        } completion: {(aMessages, aError) in
            //发送消息完成，aError为空则为发送成功
            print(aError as Any)
            if let error = aError {
                // 处理错误
                result(error.errorDescription)
            } else if aMessages != nil {
                // 获取到消息 messages
                result(MessageManage.messageToMap(message: message!))
            }
        }

    }


    //TODO
    public func sendVoiceMeesage(arguments: [String:Any],result: @escaping FlutterResult){

        let filePath = arguments["filePath"] as? String ?? ""
        let toUser = arguments["to"] as? String ?? ""
        let length = arguments["length"] as? String ?? "0"
        let message = HDMessage.createVoiceSend(withLocalPath: filePath, duration: Int32(Int(length) ?? 0), to: toUser)
        HDClient.shared().chatManager.send(message) { progress in
            //发送消息进度 Image
            print(progress)

        } completion: {(aMessages, aError) in
            //发送消息完成，aError为空则为发送成功
            print(aError as Any)
            if let error = aError {
                // 处理错误
                result(error.errorDescription)
            } else if aMessages != nil {
                // 获取到消息 messages
                result(MessageManage.messageToMap(message: message!))
            }
        }

    }


    //TODO
    public func sendFileMeesage(arguments: [String:Any],result: @escaping FlutterResult){

        let filePath = arguments["filePath"] as? String ?? ""
        let toUser = arguments["to"] as? String ?? ""
        let message = HDMessage.createFileSend(withLocalPath: filePath, to: toUser)
        HDClient.shared().chatManager.send(message) { progress in
            //发送消息进度 Image
            print(progress)

        } completion: {(aMessages, aError) in
            //发送消息完成，aError为空则为发送成功
            print(aError as Any)
            if let error = aError {
                // 处理错误
                result(error.errorDescription)
            } else if aMessages != nil {
                // 获取到消息 messages
                result(MessageManage.messageToMap(message: message!))
            }
        }

    }





    func currentTimeString() -> String {
        let timestamp = Date().timeIntervalSince1970
        let timestampString = String(format: "%.0f", timestamp)
        return timestampString
    }


}
